#include"usingHeader.hpp"

//这个用来从文件中读取内容，传输到管道内

int main(){
    //获取当前要备份的文件名
    string origin_name = origin_file + file_category;

    //创建一个管道文件
    umask(0);
    int mkPipe = mkfifo(pipe_name.c_str(), 0666);
    if(mkPipe < 0){
        ERR_EXIT("mkPipe");
    }
    else{
        cout << "创建管道文件fifo_bak成功" << endl;
    }

    //以只写的方式打开管道文件 -> 方便写入
    int fd_pipe = open(pipe_name.c_str(), O_WRONLY);
    if(fd_pipe < 0){
        ERR_EXIT("open pipe");
    }
    else{
        cout << "成功打开管道文件(O_WRONLY)" << endl;
    }

    //以只读方式打开要被备份的文件
    int fd = open(origin_name.c_str(), O_RDONLY);
    if(fd < 0){
        ERR_EXIT("open origin_file");
    }
    else{
        cout << "成功打开需要备份的文件：" << origin_name << endl;
    }

    int rd  = 0;
    char buffer[1024] = {0};
    while((rd = read(fd, buffer, sizeof(buffer))) > 0){
        int wd = write(fd_pipe, buffer, strlen(buffer));
        if(wd < 0){
            ERR_EXIT("write to pipe");
        }
    }
    if(rd == 0){
        cout << "文件已经全部写入管道" << endl;
    }
    if(rd < 0){
        ERR_EXIT("read from pipe");
    }


    return 0;
}